<?php
/*--------------------------------------------------------------------
 度咪科技 - 让工作更轻松快乐
 --------------------------------------------------------------*/

namespace Home\Controller;

use Think\Controller;

class WechatController extends Controller
{
    protected $config = array('app_type' => 'none');
    protected $needAuth = false; // 控制器是否需要验证用户信息

    private $_userInfo = null;

    private $_qywechat = null;

    public function _initialize()
    {
        if (!$this->needAuth) {
            return;
        }

        $this->_qywechat = getQyWechatObj();

        if (isset($_GET['state']) and $_GET['state'] == 'WechatOAuth') { // 验证回调
            /**
             * 这里的 userid 是微信企业号文档的 userid，如 zhangsan
             *
             * @var string
             */
            $userId = $this->_qywechat->getUserId($_GET['code']);

            if (empty($userId)) { // 不是企业成员
                die('非企业号成员');
            }

            $_SESSION['wx_userid'] = $userId;
        }

        if (!isset($_SESSION['wx_userid']) or empty($_SESSION['wx_userid'])) {
            header('Location: '.$this->_qywechat->getJumpOAuthUrl('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']));
            exit;
        } elseif (!isset($_SESSION['wx_user']) or empty($_SESSION['wx_user'])) {
            $_SESSION['wx_user'] = $this->_qywechat->getUserInfo($_SESSION['wx_userid']);
        }

        $this->_userInfo = $_SESSION['wx_user'];

        $user =  M('User')-> where(['emp_no' => ['eq', $_SESSION['wx_userid']]])->find();
        session(C("USER_AUTH_KEY"), $user['id']);
        session('emp_no', $user['emp_no']);
        session('user_name', $user['name']);
        session('dept_id', $user['dept_id']);
        session('position_id', $user['position_id']);
    }

    public function getUserInfo()
    {
        return $this->_userInfo;
    }

    public function getQywechat()
    {
        return $this->_qywechat;
    }
}
